package com.stable.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.TimeUnit;

public class TradeDateUtil {

    static String tradeUrl = "http://www.szse.cn/api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=1799_jyrl&txtFsrq=YYYY-MM-DD&random=0.7445103299670564";

    //<code,currentPrice>
    static Cache<String, String> cacheTradeDate = CacheBuilder.newBuilder()
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .maximumSize(10)
            .build();

    /**
     * 得到最近的1个交易日
     * @param before
     * @return
     */
    public static String getNearTradeDate(int before) {
        String tradeDateCache = cacheTradeDate.getIfPresent("tradeDateCache");
        if (StringUtils.isNotBlank(tradeDateCache)) {
            return tradeDateCache;
        }

        String datetime = DateUtil.convertDate(DateUtil.getTodayBeforNDayYYYYMMDD(before));
        String replaceUrl = tradeUrl.replace("YYYY-MM-DD", datetime);
        String result = HttpUtil.doGet2(replaceUrl);

        JSONArray array = JSONArray.parseArray(result);
        for (int i = 0; i < array.size(); i++) {
            Object o = array.get(i);
            JSONArray data = ((JSONObject) o).getJSONArray("data");
            if (data.size() == 0) {
                return getNearTradeDate(before + 1);
            } else {
                cacheTradeDate.put("tradeDateCache", datetime);
                return datetime;
            }
        }
        return datetime;
    }

    public static void main(String[] args) {
        System.out.println(TradeDateUtil.getNearTradeDate(0));
    }
}
